package org.caijin.springzookeeper.Client;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZkClientDemo {
    public final static String cluster_connection = "192.168.88.100:2181,192.168.88.101:2181,192.168.88.102:2181";

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        ZooKeeper zooKeeper = create(cluster_connection);
        Stat stat = zooKeeper.exists("/user", false);
        if (null == stat) {
            // 创建持久节点
            zooKeeper.create("/user","caijin".getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        // 永久监听
        zooKeeper.addWatch("/user", new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent);
            }
        },AddWatchMode.PERSISTENT);

        stat = new Stat();
        byte[] data = zooKeeper.getData("/user", false, stat);
        System.out.println("data: "+new String(data));

        // 带版本更新
        int version = stat.getVersion();
        zooKeeper.setData("/user", "hello world".getBytes(), version);
    }

    public static ZooKeeper create(String cluster_connection) throws IOException, InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        ZooKeeper zooKeeper = new ZooKeeper(cluster_connection, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                if(watchedEvent.getState() == Event.KeeperState.SyncConnected&&watchedEvent.getType()==Event.EventType.None){
                    latch.countDown();
                    System.out.println("连接建立成功！");
                }
            }
        });
        System.out.println("连接中....!");
        latch.await();
        return zooKeeper;
    }

}
